package com.example.qxfw.yjqx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.qxfw.common.entity.yj.Emergency;
import com.example.qxfw.common.entity.zy.BaseProduct;
import com.example.qxfw.mongodb.hy.service.DocFileService;
import com.example.qxfw.ybzz.mapper.BaseProductMapper;
import com.example.qxfw.yjqx.mapper.EmergencyMapper;
import com.example.qxfw.yjqx.service.EmergencyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

@Service
public class EmergencyServiceImpl implements EmergencyService {

    @Autowired
    private EmergencyMapper emergencyMapper;

    @Autowired
    private BaseProductMapper baseProductMapper;

    @Autowired
    private DocFileService docFileService;

    @Override
    public String getMaxId() {
        return emergencyMapper.getMaxId();
    }

    @Override
    public List<Emergency> getList(String type,String time1,String time2) {
        if (type == null || type.isEmpty() || type.equals("全部")){
            return emergencyMapper.selectList(new LambdaQueryWrapper<Emergency>()
            .between(Emergency::getDatetime, Timestamp.valueOf(time1),Timestamp.valueOf(time2))
                    .orderByDesc(Emergency::getId));
        }else {
            return emergencyMapper.selectList1(type, Timestamp.valueOf(time1),Timestamp.valueOf(time2));
        }
    }

    @Override
    public List<String> getDocPath(String id) {
        return emergencyMapper.selectDocPath(id);
    }

    @Override
    public Integer save(Emergency emergency) {

        return emergencyMapper.insert(emergency);
    }

    @Override
    public Integer update(Emergency emergency) {
        int id = emergency.getId();
        emergency.setId(null);
        return emergencyMapper.update(emergency, Wrappers.<Emergency>lambdaUpdate()
                .eq(Emergency::getId,id));
    }

    @Override
    public Integer delete(Integer id) {
        //获取产品信息
        Emergency emergency = emergencyMapper.selectById(id);
        List<BaseProduct> baseProducts = baseProductMapper.selectList(Wrappers.<BaseProduct>lambdaQuery().eq(BaseProduct::getProductname, emergency.getDocpath()));
        if (baseProducts.size()>0){
            //删除文档
            docFileService.deleteByTableIdAndName(String.valueOf(baseProducts.get(0).getId()),"base_product");
            //删除产品
            baseProductMapper.deleteById(baseProducts.get(0).getId());
        }
        return emergencyMapper.delete(Wrappers.<Emergency>lambdaQuery()
                .eq(Emergency::getId,id));
    }


}
